<!-- 海关编码增改弹窗 -->

<style lang="scss" scoped>
.el-form {
  .el-form-item {
    margin: 15px 0;
  }

  .hjd-drawer__footer {
    margin-top: 50px;
  }
}

.el-select,
.el-cascader {
  &, ::v-deep .el-input {
    width: 100%;
  }
}
</style>

<template>
  <el-drawer
    ref="drawer"
    custom-class="hjd-drawer"
    size="30%"
    :title="`${status === 'create' ? '新增' : '编辑'}词语`"
    :visible.sync="showDialog"
    :wrapper-closable="true"
    @close="$emit('update:visible', false)"
  >
    <div class="hjd-drawer__content">
      <el-form ref="dataForm" :model="form" label-width="100px" style="margin-left: 20px; margin-right: 20px;">
        <el-form-item label="词语" prop="search_keyword">
          <el-input v-model="form.search_keyword" />
        </el-form-item>

        <el-form-item label="绑定品牌" prop="bind_brand_id">
          <el-select
            v-model="form.bind_brand_id"
            v-loading="brand.loading"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="(val) => searchMethod('brand', val)"
          >
            <el-option
              v-for="item in brand.list"
              :key="item.brand_id"
              :label="item.brand_name"
              :value="item.brand_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="绑定商品" prop="bind_product_id">
          <el-select
            v-model="form.bind_product_id"
            v-loading="product.loading"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="(val) => searchMethod('product', val)"
          >
            <el-option
              v-for="item in product.list"
              :key="item.product_id"
              :label="item.name_zh"
              :value="item.product_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="绑定行邮税号" prop="bind_tariff_id">
          <el-cascader
            v-model="form.bind_tariff_id"
            :options="tariff.list"
            :props="{ label: 'name', value: 'id', emitPath: false, checkStrictly: true }"
            filterable
          />
        </el-form-item>

        <el-form-item label="绑定海关编码" prop="bind_hscode_id">
          <el-select
            v-model="form.bind_hscode_id"
            v-loading="hscode.loading"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="(val) => searchMethod('hscode', val)"
          >
            <el-option
              v-for="item in hscode.list"
              :key="item.hscode_id"
              :label="item.name"
              :value="item.hscode_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item>

        <div class="hjd-drawer__footer">
          <el-button @click="showDialog = false">
            取消
          </el-button>
          <el-button type="primary" @click="submit">
            确定
          </el-button>
        </div>

      </el-form>
    </div>
  </el-drawer>
</template>

<script>

import _ from 'lodash'

import { addSearchWord, editSearchWord } from '@/api/base/search'

import { handleList as getBrandList } from '@/api/base/brand'
import { handleList as getProductList } from '@/api/base/product'
import { listsArea as getTariffList } from '@/api/tariff'
import { hscodeList as getHscodeList } from '@/api/base/hscode'

export default {
  name: 'UpdateSearchDialog',

  props: {
    visible: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: 'new'
    },
    data: {
      type: Object,
      default: () => ({})
    }

    /** 默认列表 */
    // defaultList: {
    //   type: Object,
    //   default: () => ({})
    // }
  },
  data() {
    return {
      showDialog: this.visible,

      beforeData: {},

      /** 商品 */
      product: {
        loading: false,
        list: []
      },

      /** 品牌 */
      brand: {
        loading: false,
        list: []
      },

      /** 行邮税号 */
      tariff: {
        loading: false,
        list: []
      },

      /** 海关编码 */
      hscode: {
        loading: false,
        list: []
      },

      /**
       * 表单内容
       */
      form: {
        search_id: 0,
        search_keyword: '',
        bind_brand_id: 0,
        bind_product_id: 0,
        bind_tariff_id: 0,
        bind_hscode_id: 0,
        goods_img: '',
        status: 0
      }
    }
  },

  created() {
    this.beforeData = _.cloneDeep(this.data)

    if (this.status === 'update') {
      const data = _.cloneDeep(this.data)
      this.form = {
        ...this.form,
        ...data
      }
    }

    _.forEach([
      'bind_brand_id',
      'bind_product_id',
      'bind_tariff_id',
      'bind_hscode_id'
    ], key => {
      if (this.form[key] === 0) {
        this.form[key] = ''
      }
    })

    // 行邮税号列表
    getTariffList({
      name: '',
      page: 0,
      pid: 0
    }).then(res => {
      this.tariff.list = res.data
    })

    // 设置默认数据
    this.product.list = [this.data.product || {}]
    this.brand.list = [this.data.brand || {}]
    this.hscode.list = [this.data.bc || {}]
  },

  methods: {

    /**
     * el-select 搜索方法
     *
     * 除了 tariff 没有搜索外，其他都会用到
     * @param {'brand' | 'product' | 'tariff' | 'hscode'} type 类型：品牌 | 商品 | 税率 | 海关编码
     */
    searchMethod(type, val) {
      console.log(type, val)

      this[type].loading = true

      let getList = null
      let params = {}

      switch (type) {
        case 'brand':
          getList = getBrandList
          params = {
            brandWhere: 'brand_name',
            limit: 100,
            page: 1,
            word: val
          }
          break

        case 'product':
          getList = getProductList
          params = {
            limit: 100,
            page: 1,
            proKeyWord: val,
            // 如果全是数字和横杠 则按 barcode 搜索 否则按 中文名称
            profield: /^(\d|-)+$/.test(val) ? 'barcode' : 'name_zh',
            taxKeyword: '',
            taxfield: 'tax_code'
          }
          break

        case 'hscode':
          getList = getHscodeList
          params = {
            limit: 100,
            page: 1,
            keyword: val
          }
          break
      }

      if (!_.isFunction(getList)) {
        this.$message.error('类型参数错误')
        return
      }

      getList(params).then(res => {
        this[type].list = _.get(res, 'data.data', [])
      }).finally(() => {
        this[type].loading = false
      })
    },

    submit() {
      // 数据没改动 直接关闭弹窗
      if (_.isEqual(this.form, this.beforeData)) {
        this.showDialog = false
        return
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 是否是创建
          const isCreate = this.status === 'create'

          // 请求数据
          const queryData = {
            search_keyword: this.form.search_keyword,
            bind_brand_id: this.form.bind_brand_id,
            bind_product_id: this.form.bind_product_id,
            bind_tariff_id: this.form.bind_tariff_id,
            bind_hscode_id: this.form.bind_hscode_id,
            goods_img: this.form.goods_img,
            status: this.form.status
          }

          // 修改时传 ID
          if (!isCreate) queryData['search_id'] = this.data.search_id

          // 请求接口
          const request = isCreate ? addSearchWord : editSearchWord
          request(queryData).then(() => {
            this.data.hscode = this.form.hscode
            this.data.name = this.form.name
            this.data.first_unit = this.form.first_unit
            this.data.second_unit = this.form.second_unit
            this.data.tax_rate = this.form.tax_rate
            this.data.status = this.form.status

            this.showDialog = false
            this.$notify.success(isCreate ? '创建成功' : '修改成功')
            // 刷新列表
            this.$emit('reload')
          })
        }
      })
    }
  }
}
</script>
